package cn.mw.cmdb.util;

import cn.mw.cmdb.enums.ZabbixItemUnitEnum;
import cn.mw.microMonitorCommon.entity.UnitResult;
import cn.mw.microMonitorCommon.util.DateUtils;
import cn.mw.microMonitorCommon.util.UnitUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.math.NumberUtils;
import org.apache.logging.log4j.util.Strings;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.Date;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author qzg
 * @date 2023/8/28
 */
@Slf4j
public class ValConvertUtil {

    public static int intValueConvert(Object value) {
        Pattern pattern = Pattern.compile("^[+]?[\\d]*$");
        if (value == null) {
            return 0;
        }
        if (Strings.isEmpty(value.toString())) {
            return 0;
        }
        boolean isNum = pattern.matcher(value.toString()).matches();
        if (isNum) {
            return Integer.valueOf(value.toString());
        }
        return 0;
    }

    public static long longValueConvert(Object value) {
        Pattern pattern = Pattern.compile("^[+]?[\\d]*$");
        if (value == null) {
            return 0l;
        }
        if (Strings.isEmpty(value.toString())) {
            return 0l;
        }
        boolean isNum = pattern.matcher(value.toString()).matches();
        if (isNum) {
            return Long.valueOf(value.toString());
        }
        return 0l;
    }

    public static String strValueConvert(Object value) {
        if (value == null) {
            return "";
        }
        return value.toString();
    }

    public static boolean booleanValueConvert(Object value) {
        boolean bool = false;
        if (value == null) {
            return bool;
        }
        bool = Boolean.parseBoolean(value.toString());
        return bool;
    }

    public static Double doubleValueConvert(Object value) {
        Pattern pattern = Pattern.compile("^[-+]?\\d*\\.?\\d+([eE][-+]?\\d+)?$");
        if (value == null) {
            return 0d;
        }
        if (Strings.isEmpty(value.toString())) {
            return 0d;
        }
        boolean isNum = pattern.matcher(value.toString()).matches();
        if (isNum) {
            return Double.valueOf(value.toString());
        }
        return 0d;
    }

    public static String readTxt(String txtPath) {
        File file = new File(txtPath);
        if (file.isFile() && file.exists()) {
            try {
                FileInputStream fileInputStream = new FileInputStream(file);
                InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream);
                BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
                StringBuffer sb = new StringBuffer();
                String text = null;
                while ((text = bufferedReader.readLine()) != null) {
                    sb.append(text);
                }
                return sb.toString();
            } catch (Exception e) {
                log.error("fail to readTxt case:{}", e);
            }
        }
        return null;
    }

    /**
     * 字符串中提取数字
     * @param str
     * @return
     */
    public static Long getNumByStr(String str) {
        Long intNum = 0l;
        if (Strings.isEmpty(str)) {
            return intNum;
        }
        String regEx = "[^0-9]";
        Pattern p = Pattern.compile(regEx);
        Matcher m = p.matcher(str);
        String strNum = m.replaceAll("").trim();
         intNum = longValueConvert(strNum);
        return intNum;
    }

    public static UnitResult valueConvertUnit(String units,String lastValue, String valuemapid,Map<String, Map> valuemapidMap){
        UnitResult unitResult = new UnitResult();
        if (NumberUtils.isNumber(lastValue)) {
            BigDecimal bValue = valueConvert(lastValue);
            if (bValue.toPlainString().indexOf(".") != -1) {
                lastValue = bValue.setScale(2, BigDecimal.ROUND_HALF_UP).toString();
            }
        }
        if (ZabbixItemUnitEnum.b.name().equals(units)) {
            units = ZabbixItemUnitEnum.B.name();
        }
        if (!Strings.isEmpty(units)) {//如果有单位，进行单位转换
            unitResult = UnitUtil.getValueAndUnits(lastValue, units);
            lastValue = unitResult.getValue();
            units = unitResult.getUnits();
        }
        //时间单位 数值处理
        if (ZabbixItemUnitEnum.uptime.name().equals(units)) {
            Long longValue = getNumByStr(lastValue);
            lastValue = SeverityUtils.getLastTime(longValue);
        }
        if (ZabbixItemUnitEnum.unixtime.name().equals(units)) {
            Long longValue = getNumByStr(lastValue);
            if (longValue < 9999999999l) {
                lastValue = DateUtils.formatDateTime(new Date(longValue * 1000L));
            } else {
                lastValue = DateUtils.formatDateTime(new Date(longValue));
            }
        }
        if (valuemapidMap != null && valuemapidMap.size() > 0 &&
                valuemapidMap.get(valuemapid) != null && valuemapidMap.get(valuemapid).get(lastValue) != null) {
            String newvalue = valuemapidMap.get(valuemapid).get(lastValue).toString();
            if (!Strings.isEmpty(newvalue)) {
                lastValue = newvalue;
            }
        }
        unitResult.setValue(lastValue);
        unitResult.setUnits(units);
        return unitResult;
    }

    private static BigDecimal valueConvert(String validNumber){
        if (validNumber.startsWith("0x") || validNumber.startsWith("0X")) {
            // 十六进制
            BigInteger decimalValue = new BigInteger(validNumber.substring(2), 16);
            return new BigDecimal(decimalValue);
        } else if (validNumber.startsWith("0b") || validNumber.startsWith("0B")) {
            // 二进制
            BigInteger decimalValue = new BigInteger(validNumber.substring(2), 2);
            return new BigDecimal(decimalValue);
        } else if (validNumber.matches("^0[0-7]*$")) {
            // 八进制
            BigInteger decimalValue = new BigInteger(validNumber, 8);
            return new BigDecimal(decimalValue);
        } else {
            // 默认认为是十进制
            return new BigDecimal(validNumber);
        }

    }


    public static Integer getDelayNum(String str) {
        int i = 0;
        if(Strings.isEmpty(str)){
            return i;
        }
        String reg = "[^0-9]";
        Pattern pattern = Pattern.compile(reg);
        Matcher m = pattern.matcher(str);
        String trim = m.replaceAll("").trim();
        String units = str.replaceAll("\\s*", "").replaceAll("[^(A-Za-z)]", "");
        if ("h".equals(units) || "H".equals(units)) {
            i = (Integer.valueOf(trim) * 60 * 60) + 1;
        }
        if ("m".equals(units) || "M".equals(units)) {
            i = (Integer.valueOf(trim) * 60) + 1;
        }
        if ("s".equals(units) || "S".equals(units)) {
            i = Integer.valueOf(trim);
        }
        return i;
    }
}
